ansible 错误处理
2022-06-14
通常情况下,当 tasks 失败后,play 将会终止,任何在前面已经被 tasks notify 的 handlers,都不会被执行。如果在 play 中设置了 force_handlers: yes 参数,被通知的 handlers 就会被强制执行。(有些特殊场景可能会使用到)
tasks 执行错误调用 handlers
- hosts: web
force_handlers: yes
tasks:
- name: touch file
file: path=/tmp/bbb state=touch
notify: restart httpd
- name: install package
yum: name=telnet state=latest
handlers:
- name: restart httpd
service: name=httpd state=restarted
关闭changed的状态
确定该tasks不会对被控端做任何的修改和变更
- hosts: web
tasks:
- name: install httpd
yum: name=httpd state=present
- name: start httpd
service: name=httpd stat=started
- name: check httpd
shell ps aux |grep httpd
register: check_httpd
# 如果不加该行,返回结果永远是 黄色的 changed 状态;
changed_when: false
- name: output variables
debug:
msg: "{{ check_httpd.stdout_lines }}"
使用 changed_when 检查 tasks 任务返回的结果
- hosts: web
tasks:
- name: install nginx
yum: name=nginx state=present
- name: config nginx
copy: src=./aaa.conf dest=/etc/nginx/nginx.conf
notify: restart nginx
- name: check nginx config
command: /usr/sbin/nginx -t
register: check_nginx
# 在变量里边查找关键字 sucdessful ,如果有,证明nginx 配置文件正确,可以重启
# 可以执行下边的 tasks 和 handler
# 关闭 chaned 变黄的警告
changed_when:
- ( check_nginx.stdout.find('successful'))
- false
- name: debug
debug:
msg: "{{ check_nginx }}"
- name: start nginx
service: name=nginx state=started
handlers:
- name: restart nginx
service: name=nginx state=restarted